//
//  ST_DailyMomentController.swift
//  btvideo
//
//  Created by mac on 2020/7/21.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftyUserDefaults

class ST_DailyMomentController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
         
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            
            self?.play_scan_view()
            self?.refresh_data()
        })
        
        binding()
        
    }
    
    private func binding(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(thumb_up_noti_handle(noti:)), name: Notification.Name.thumbUpDaily, object: nil)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.currentPage = 0
                own.request_data()
            }else{
                own.clear_data()
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    
    func clear_data(){
        
        self.pause_video()
        
        self.data_array.removeAll()
        
        self.tableView.reloadData()
        
    }
    
    @objc fileprivate func thumb_up_noti_handle(noti:Notification){
        
        
        //        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController,vc != self else{
            return
        }
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool else{
            return
        }
        
        guard let idx = data_array.firstIndex(where: {$0.id.string == id}) else{
            return
        }
        
        let index = Int(idx.uInt)
        
        data_array[safe: index]?.isThumbUp = isThumbUp
        
        if isThumbUp{
            data_array[safe: index]?.thumpCount += 1
        }else{
            data_array[safe: index]?.thumpCount -= 1
        }
        
        self.pause_video()
        
        self.tableView.reloadRows(at: [IndexPath.init(row: index, section: 0)], with: UITableView.RowAnimation.fade)
        
    }
    //    MARK: - Properties
    
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 10 + 49 , right: 0)
        
        control.delegate = self
        control.dataSource = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        control.estimatedRowHeight = 0
        control.estimatedSectionFooterHeight = 0
        control.estimatedSectionHeaderHeight = 0
        
        control.register(cellWithClass: ST_DailyMomentCell.self)
        control.register(headerFooterViewClassWith: ST_DailyMomentSectionHeader.self)
        
        control.separatorStyle = .none
        
        control.backgroundColor = .white
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.tableHeaderView = self.headerView
        
        return control
    }()
    
    
    fileprivate lazy var headerView:ST_DailyMomentHeaderView = {
        let control = ST_DailyMomentHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ST_DailyMomentHeaderView.height))
        return control
    }()

    //    MARK:- Play Operation
    fileprivate var current_play_index_path:IndexPath?
    
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 15
        return control
    }()
    
    fileprivate func play(indexPath:IndexPath){
            
        pause_video()
        
        guard let cell = tableView.cellForRow(at: indexPath) as? ST_DailyMomentCell , let dataItem = data_array[safe:indexPath.item],let media = dataItem.contentImages.first else{return}
        
        
        
        if media.videoUrl.count < 2{
            
            return
        }
            
        cell.contentView.addSubview(playerView)
        
        let rect = CGRect.init(origin: CGPoint.init(x: 69, y: 70), size: dataItem.mediaSize)
         
        playerView.frame = rect
        
        
        
        let currModel = ST_PairsShareParticularModel.init(imageUrl: media.content, videoUrl: media.videoUrl, width: dataItem.mediaSize.width, height: dataItem.mediaSize.height)
        
        playerView.setUp(data_array: [currModel])
        
        current_play_index_path = indexPath
    }
    
    fileprivate func pause_video(){
        
        if playerView.frame.width == ScreenWidth{
            return
        }
        playerView.clear_data()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
        
        current_play_index_path = nil
    }
    
    
    /**
     找出可以播放的indexPath
     */
    fileprivate func find_can_play_index_path(determineContinueBlock:((UITableViewCell)->(Bool)))->IndexPath?{
        
        var foundIndex:IndexPath?
        
        for item in tableView.visibleCells {
            
            if determineContinueBlock(item){
                continue
            }
            
            if let cell = item as? ST_DailyMomentCell,cell.model?.contentImages.first?.videoUrl.count ?? 0 > 2{
                
                if let playIdx = tableView.indexPath(for: cell){
                    
                    if let last = foundIndex,last.item < playIdx.item{
                        continue
                    }
                    
                    let rectInScreen = tableView.convert(cell.frame, to: nil)
                    
                    let intersect = containerRect.intersection(rectInScreen)
                    
                    let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
                    //               小于 70% 换下一个哈
                    if percent < 0.8{
                        continue
                    }
                    
                    foundIndex = playIdx
                }
            }
        }
        
        return foundIndex
    }
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
    
    /**
     确定播放下一个indexPath
     */
    fileprivate func determined_will_play_index_path()->IndexPath?{
        
        var foundIndex:IndexPath?
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let currCell = tableView.cellForRow(at: curr){
            
            let rectInScreen = tableView.convert(currCell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
            //               大于 50% 还是展示自己
            if percent > 0.5{
                return curr
            }else{
                foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                    return item == currCell
                })
            }
        }else{
            
            // 取出第一个 video cell 播放
            foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                return false
            })
        }
        
        print("cell视频---切换到另外一个Item:",foundIndex?.item ?? "🈚️")
        
        return foundIndex
    }
    
    //    MARK: - Data
    fileprivate var currentPage = 0
    
    fileprivate var data_array = [DailyMomentOfHallModel]()
    
    /**
     1:最新,2:推荐(默认)
     */
//    fileprivate var dataType = 2
    
    fileprivate var filterSEX = ST_SEX.both
    
    func filter_remote_data(sex:ST_SEX){
        
        if filterSEX.rawValue == sex.rawValue{
            return
        }
        
        filterSEX = sex
        
        
        refresh_data()
    }
    
    @objc  func refresh_data(){
        
        currentPage = 0
        
        
        
        self.tableView.setContentOffset(CGPoint.zero, animated: true)
        
        self.request_data()
        
        self.headerView.request_data()
    }
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        if currentPage == 1{
            if scan_root_view.superview == nil{
                play_scan_view()
            }
        }
        
        let param = ["page":currentPage,
                     "show_state":2,
                     "daily_type":self.filterSEX.rawValue,
                     "size":20]
        
        self.pause_video()
        
        JVrequest(PH.recommendDailyApi,parameters: param, success: { (json) in
            
            print("看看 数据呢：",json)
            
            let data = json["data"]
            
            let list = data["list"].arrayValue.map { (itemJson) -> DailyMomentOfHallModel in
                return DailyMomentOfHallModel.init(fromJson: itemJson)
            }
            
            if self.currentPage == 1{
                self.data_array = list
            }else{
                self.data_array += list
            }
            
            self.stop_scan_view()
            
            self.tableView.reloadData {
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
            
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            
            self.tableView.footer_refresh(count: list.count) {[weak self] in
                
                self?.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_data()
                })
            }
            
            
        }) { (code, err) in
            print("看看 数据呢-error：",err)
            self.toast(text: err)
        }
        
    }
    
    
    
    
    //    MARk: - scan UI
    fileprivate func stop_scan_view(){
        
        scan_root_view.isHidden = true
        scan_animate_view.stop()
        
    }
    
    fileprivate func play_scan_view(){
        
        if scan_root_view.superview == nil{
            view.insertSubview(scan_root_view, aboveSubview: tableView)
            scan_root_view.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            
            
            scan_root_view.addSubview(scan_animate_view)
            scan_animate_view.snp.makeConstraints { (make) in
                make.width.height.equalTo(50/375.0*ScreenWidth)
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview()
            }
        }
        scan_root_view.isHidden = false
        scan_animate_view.play()
    }
    
    
    
    fileprivate lazy var scan_root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        return control
    }()
    
    fileprivate lazy var scan_animate_view:LOTAnimationView = {
        
        let path = Bundle.main.path(forResource: "homeSearchAnimation", ofType: "json")!
        
        let control = LOTAnimationView.init(filePath: path)
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        
        control.loopAnimation = true
        
        return control
    }()
}


extension ST_DailyMomentController:UITableViewDelegate,UITableViewDataSource{
    
    /*
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = tableView.dequeueReusableHeaderFooterView(withClass: ST_DailyMomentSectionHeader.self)
        
        
        view.selectClosure = {[weak self] index in
            
            self?.dataType = index
            
            self?.currentPage = 0
            
            self?.request_data()
            
            self?.tableView.scrollToTop()
        }
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 64 - 15 - 10
    }
    
    */
    
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    
        let a = self.data_array.count - indexPath.row
        
        
        if a <= 5 {
            
            self.tableView.mj_footer?.beginRefreshing()
            
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
//        print("移除了:",indexPath)
        
        if let last = current_play_index_path,last.row == indexPath.row{
            self.pause_video()
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: ST_DailyMomentCell.self, for: indexPath)
        
        cell.model = data_array[indexPath.row]
        
        cell.reload_cell_closure = {[weak self] in

            if #available(iOS 13.0, *) {
                self?.tableView.reloadData()
            } else {
                self?.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.fade)
            }
        }
        
        
        cell.comment_click_closure = {[weak self] iCell in
            
            guard let model = iCell.model else{ return }
            
            let vc = ST_DaliyMomentDetailController()
            
            vc.dailyId = model.id.string
            
            vc.userId = model.accid
            
            vc.openInputCommentBar = true
            
            self?.navigationController?.pushViewController(vc)
        }
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return data_array[indexPath.row].cellHeight
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = data_array[indexPath.row]
        
        let vc = ST_DaliyMomentDetailController()
        
        vc.dailyId = model.id.string
        
        vc.userId = model.accid
        
        self.navigationController?.pushViewController(vc)
        
    }
    
    
    //    MARK: Scroll Delegate
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let cell = tableView.cellForRow(at: curr){
            
            let rectInScreen = tableView.convert(cell.frame, to: nil)
            
            if containerRect.intersects(rectInScreen) == false{
                pause_video()
            }
        }
        
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
            scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        scrollviewdidEndScroll(scrollView)
        
    }
    
    //    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        guard let willPlayIdx = determined_will_play_index_path() else {
            
            pause_video()
            
            return
        }
        
        if let curr = current_play_index_path,curr.item == willPlayIdx.item{
            return
        }
        
        play(indexPath: willPlayIdx)
        
    }
}
